import matplotlib
import pandas as pd
import xlrd
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import numpy as np
import time
import math
import copy

from PIL import Image

from utils.index import resource_path
from .gain import gain
from .seismic import Seismic


matplotlib.use('Agg')  # 使用非交互模式

def vspplot(cfg, progress_wrapper):
    #####################################################################
    # READ SEGY
    #####################################################################
    start = time.time()
    progress_wrapper.setValue(0)
    # s1 = Seismic.from_segy(cfg['lp'])
    s2 = Seismic.from_segy(cfg['lp2'])  # 反褶积前拉平，读取
    s3 = Seismic.from_segy(cfg['lp3'])  # 反褶积后拉平，读取
    s4 = Seismic.from_segy(cfg['stk'])  # 走廊文件，读取
    s5 = Seismic.from_segy(cfg['stkbf'])  # 滤波走廊文件，读取
    s6 = Seismic.from_segy(cfg['sei'])  # 地面文件，读取
    end = time.time()
    print('文件读取时间：', end - start)

    print('************************')
    print("Read OK!")
    print("Start Agc!")

    if cfg['lpjx'] == 0:
        # s1.data = -s1.data
        s2.data = -s2.data
        s3.data = -s3.data
    if cfg['stkjx'] == 0:
        s4.data = -s4.data
    if cfg['stkbfjx'] == 0:
        s5.data = -s5.data
    if cfg['seijx'] == 0:
        s6.data = -s6.data

    # if s1.dt < 1:
    #     sca = int(1 / s1.dt)
    #     s1.dt = 1.0
    #     s1.data = s1.data[::, ::sca]
    if s2.dt < 1:
        sca = int(1 / s2.dt)
        s2.dt = 1.0
        s2.data = s2.data[::, ::sca]
    if s3.dt < 1:
        sca = int(1 / s3.dt)
        s3.dt = 1.0
        s3.data = s3.data[::, ::sca]

    # if cfg['lpagc'] == 0:
    #     start = time.time()
    #     s1.data = gain(s1.data, s1.dt, 'agc', cfg['agc'], 1)
    #     end = time.time()
    #     print('************************')
    #     print("拉平 AGC OK!", start - end)
    if cfg['lp2agc'] == 0:
        start = time.time()
        s2.data = gain(s2.data, s2.dt, 'agc', cfg['agc'], 1)
        end = time.time()
        print('************************')
        print("拉平2 AGC OK!", start - end)
    if cfg['lp3agc'] == 0:
        start = time.time()
        s3.data = gain(s3.data, s3.dt, 'agc', cfg['agc'], 1)
        end = time.time()
        print('************************')
        print("拉平3 AGC OK!", start - end)

    if cfg['stkagc'] == 0:
        start = time.time()
        s4.data = gain(s4.data, s4.dt, 'agc', cfg['agc'], 1)
        end = time.time()
        print('************************')
        print("走廊 AGC OK!", start - end)

    if cfg['stkbfagc'] == 0:
        start = time.time()
        s5.data = gain(s5.data, s5.dt, 'agc', cfg['agc'], 1)
        end = time.time()
        print('************************')
        print("滤波走廊 AGC OK!", start - end)

    if cfg['seiagc'] == 0:
        start = time.time()
        s6.data = gain(s6.data, s6.dt, 'agc', cfg['agc'], 1)
        print(s6.data, 'cccccc')
        end = time.time()
        print('************************')
        print("地面地震 AGC OK!", start - end)

    print('************************')
    print("Start Plot!")

    if cfg['fcx'] == 1:
        df = pd.read_excel(cfg['fc'], sheet_name=0)  # sheet_name指定工作表编号或名称
        df.fillna('', inplace=True)  # 如果为空，则替换为空字符串
        dep = df.iloc[:, 1]  # 获取第一列的内容
        zu = df.iloc[:, 0]
        font = df.iloc[:, 2]
        py = df.iloc[:, 3]
    else:
        dep = []
        zu = []
        font = []
        py = []

    #####################################################################
    # MAKE PLOT
    #####################################################################

    # Plot size parameters.

    # Margins, CSS like: top, right, bottom, left.
    mt, mr, mb, ml = 0.3, 0.5, 0.3, 0.5

    # Determine plot dimensions. Kind of laborious and repetitive (see below).
    tpi = cfg['tpi']
    tpis = cfg['tpis']
    ips = cfg['ips']

    # 需要根据加密情况计算宽度

    seismic_height_raw = ips * (cfg['trange'][1] - cfg['trange'][0])
    w1 = (cfg['lped'] - cfg['lpsd']) / (20 * tpi)
    w2 = w1
    w3 = w1
    w4 = (cfg['sein'] + 1) / tpis
    w5 =10 / tpi
    w6 =10 / tpi
    w7 = (cfg['sein'] + 1) / tpis

    stkcdp = 0
    maxjuli = 999999999.0
    for i in range(s6.ntraces):
        juli = math.sqrt((s4.wellx[0] * 1.0 - s6.cdpx[i]) ** 2 + (s4.welly[0] * 1.0 - s6.cdpy[i]) ** 2)
        if juli < maxjuli:
            maxjuli = juli
            stkcdp = i

    print(stkcdp, maxjuli)

    h = seismic_height_raw
    # seismic_width = w1 + w2 + w3 + w4 + w5 + w6 + w7 + mr + ml
    seismic_width = w2 + w3 + w4 + w5 + w6 + w7 + mr + ml
    seismic_left = ml / seismic_width
    seismic_bottom = (mb / h)

    # seismic_width_fraction1 = w1 / seismic_width
    seismic_width_fraction2 = w2 / seismic_width
    seismic_width_fraction3 = w3 / seismic_width
    seismic_width_fraction4 = w4 / seismic_width
    seismic_width_fraction5 = w5 / seismic_width
    seismic_width_fraction6 = w6 / seismic_width
    seismic_width_fraction7 = w7 / seismic_width

    seismic_height_fraction = seismic_height_raw / h

    w = seismic_width

    # Set the tickformat.
    # tickfmt = mtick.FormatStrFormatter('%.0f')

    # cfg['fontsize'] = cfg['fontsize'] or 30

    # config = {
    #     "font.family": 'serif',
    #     "font.size": 20,
    #     "mathtext.fontset": 'stix',
    #     "font.sans-serif": 'SimSun',
    # }

    plt.rcParams['font.sans-serif'] = ['SimHei']  # 显示中文标签
    plt.rcParams['mathtext.default'] = 'regular'
    plt.rcParams['axes.unicode_minus'] = False

    fig = plt.figure(figsize=(w, h), facecolor='w', dpi=300)

    # rect_line1 = [seismic_left, seismic_bottom, seismic_width_fraction1,
    #               seismic_height_fraction]
    rect_line2 = [seismic_left, seismic_bottom,
                  seismic_width_fraction2, seismic_height_fraction]
    rect_line3 = [seismic_left + seismic_width_fraction2,
                  seismic_bottom, seismic_width_fraction3, seismic_height_fraction]
    rect_line4 = [seismic_left + seismic_width_fraction2 + seismic_width_fraction3,
                  seismic_bottom, seismic_width_fraction4, seismic_height_fraction]
    rect_line5 = [seismic_left + seismic_width_fraction2 + seismic_width_fraction3 +
                  seismic_width_fraction4, seismic_bottom, seismic_width_fraction5, seismic_height_fraction]
    rect_line6 = [seismic_left + seismic_width_fraction2 + seismic_width_fraction3 +
                  seismic_width_fraction4 + seismic_width_fraction5, seismic_bottom, seismic_width_fraction6,
                  seismic_height_fraction]
    rect_line7 = [seismic_left + seismic_width_fraction2 + seismic_width_fraction3 +
                  seismic_width_fraction4 + seismic_width_fraction5 + seismic_width_fraction6, seismic_bottom,
                  seismic_width_fraction7, seismic_height_fraction]

    # ax1 = fig.add_axes(rect_line1)
    ax2 = fig.add_axes(rect_line2)
    ax3 = fig.add_axes(rect_line3)
    ax4 = fig.add_axes(rect_line4)
    ax5 = fig.add_axes(rect_line5)
    ax6 = fig.add_axes(rect_line6)
    ax7 = fig.add_axes(rect_line7)

    # ax2.set_yticks([])
    ax3.set_yticks([])
    ax4.set_yticks([])
    ax5.set_yticks([])
    ax6.set_yticks([])
    ax5.set_xticks([])
    ax6.set_xticks([])

    # ax1.xaxis.set_ticks_position('top')
    ax2.xaxis.set_ticks_position('top')
    ax3.xaxis.set_ticks_position('top')
    ax4.xaxis.set_ticks_position('top')
    ax7.xaxis.set_ticks_position('top')
    ax7.yaxis.set_ticks_position('right')

    ax2.spines['right'].set_visible(False)
    ax3.spines['right'].set_visible(False)
    ax4.spines['right'].set_visible(False)
    ax5.spines['right'].set_visible(False)
    ax6.spines['right'].set_visible(False)

    # ax1 = s1.imshow2(
    #     ax=ax1,
    #     gain=cfg['lpgain'],
    #     ts=cfg['trange'][0],
    #     td=cfg['trange'][1],
    #     lped=cfg['lped'],
    #     lpsd=cfg['lpsd'],
    #     secai=cfg['sc'],
    # )
    # print('************************')
    # print("拉平1 Plot OK!")
    ax2 = s2.imshow2(
        ax=ax2,
        gain=cfg['lp2gain'],
        ts=cfg['trange'][0],
        td=cfg['trange'][1],
        lped=cfg['lped'],
        lpsd=cfg['lpsd'],
        secai=cfg['sc'],
    )
    print('************************')
    print("拉平2 Plot OK!")
    [fbmin, fbmax, ax3, fctime] = s3.imshow(
        ax=ax3,
        gain=cfg['lp3gain'],
        ts=cfg['trange'][0],
        td=cfg['trange'][1],
        fcx=cfg['fcx'],
        lped=cfg['lped'],
        lpsd=cfg['lpsd'],
        dep=dep,
        kb=cfg['kb'],
        secai=cfg['sc'],
    )
    print('************************')
    print("拉平3 Plot OK!")

    ax4 = s6.wiggle_plot2(
        ax=ax4,
        gain=cfg['seigain'],
        rgb=cfg['colour'],
        alpha=cfg['opacity'],
        lw=cfg['lineweight'],
        ts=cfg['trange'][0],
        td=cfg['trange'][1],
        times=cfg['seitimes'],
        stt=stkcdp,
        sein=cfg['sein'],
        fcx=cfg['fcx'],
        fctime=fctime,
        fbmin=fbmin,
        fbmax=fbmax,
        sttflag=1,
        plotzflag=0,
    )

    ax5 = s4.wiggle_plot2(
        ax=ax5,
        gain=cfg['stkgain'],
        rgb=cfg['colour'],
        alpha=cfg['opacity'],
        lw=cfg['lineweight'],
        ts=cfg['trange'][0],
        td=cfg['trange'][1],
        times=0,
        stt=0,
        sein=9,
        fcx=cfg['fcx'],
        fctime=fctime,
        fbmin=fbmin,
        fbmax=fbmax,
        sttflag=0,
        plotzflag=0,
    )
    ax6 = s5.wiggle_plot2(
        ax=ax6,
        gain=cfg['stkbfgain'],
        rgb=cfg['colour'],
        alpha=cfg['opacity'],
        lw=cfg['lineweight'],
        ts=cfg['trange'][0],
        td=cfg['trange'][1],
        times=cfg['times'],
        stt=0,
        sein=9,
        fcx=cfg['fcx'],
        fctime=fctime,
        fbmin=fbmin,
        fbmax=fbmax,
        sttflag=0,
        plotzflag=0,
    )
    ax7 = s6.wiggle_plot2(
        ax=ax7,
        gain=cfg['seigain'],
        rgb=cfg['colour'],
        alpha=cfg['opacity'],
        lw=cfg['lineweight'],
        ts=cfg['trange'][0],
        td=cfg['trange'][1],
        times=cfg['seitimes'],
        stt=stkcdp,
        sein=cfg['sein'],
        fcx=cfg['fcx'],
        zu=zu,
        py=py,
        font=font,
        fctime=fctime,
        fbmin=fbmin,
        fbmax=fbmax,
        plotzflag=1,
        sttflag=0,
    )

    ax4.set_ylim(1000 * cfg['trange'][1] + cfg['seitimes'] or 1000 * s2.tbasis[-1],
                 1000 * cfg['trange'][0] + cfg['seitimes'])
    ax5.set_ylim(1000 * cfg['trange'][1] or 1000 * s2.tbasis[-1],
                 1000 * cfg['trange'][0])
    ax6.set_ylim(1000 * cfg['trange'][1] + cfg['seitimes'] or 1000 * s2.tbasis[-1],
                 1000 * cfg['trange'][0] + cfg['seitimes'])
    ax7.set_ylim(1000 * cfg['trange'][1] + cfg['seitimes'] or 1000 * s2.tbasis[-1],
                 1000 * cfg['trange'][0] + cfg['seitimes'])
    print('************************')
    print("地面地震 Plot OK!")
    print("Start Save!")

    ticks_loc = np.arange(20, 20 * (cfg['sein']) + 20, 300)
    ax4.set_xticks(ticks_loc)
    ticklable = s6.cdp[(stkcdp - cfg['sein']):stkcdp:15]
    ax4.set_xticklabels(ticklable, fontsize=cfg['fontsize'] - 20)


    ticks_loc = np.arange(20, 20 * (cfg['sein']) + 20, 300)
    ax7.set_xticks(ticks_loc)
    ticklable = s6.cdp[stkcdp:stkcdp + cfg['sein'] :15]
    ax7.set_xticklabels(ticklable, fontsize=cfg['fontsize'] - 20)


    #####################################################################
    # SAVE FILE
    #####################################################################

    # outfile = cfg['outfile']
    # # fig.savefig(outfile, bbox_inches='tight', transparent=True)
    # fig.savefig(outfile, bbox_inches='tight', )

    outfile = resource_path("./static/img/provisional.png")
    fig.savefig(outfile, bbox_inches='tight')  # 支持eps, jpeg, jpg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff, webp
    image = Image.open(outfile)
    image.save(cfg['outfile'])

    print(time.time() - start, '完成')
    progress_wrapper.setValue(100)
    print('************************')
    print("保存完成")
    print('************************')
    return


def mulWaveDiagram(cfg, progress_wrapper):
    data_copy = copy.deepcopy(cfg)
    start = time.time()

    data_copy['tpi'] = cfg['tpi'] * 2.54
    data_copy['ips'] = cfg['ips'] / 2.54
    data_copy['tpis'] = cfg['tpis'] * 2.54
    data_copy['sc'] = "gray_r"

    vspplot(data_copy, progress_wrapper)

    end = time.time()
    print(f'多次波运行时长：{end - start}秒')
    return {
        'status': 'success'
    }